

<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  <title>nlp_architect.models.transformers.sequence_classification &mdash; NLP Architect by Intel® AI Lab 0.5.2 documentation</title>
  

  
  
  
  

  
  <script type="text/javascript" src="../../../../_static/js/modernizr.min.js"></script>
  
    
      <script type="text/javascript" id="documentation_options" data-url_root="../../../../" src="../../../../_static/documentation_options.js"></script>
        <script type="text/javascript" src="../../../../_static/jquery.js"></script>
        <script type="text/javascript" src="../../../../_static/underscore.js"></script>
        <script type="text/javascript" src="../../../../_static/doctools.js"></script>
        <script type="text/javascript" src="../../../../_static/language_data.js"></script>
        <script type="text/javascript" src="../../../../_static/install.js"></script>
        <script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
    
    <script type="text/javascript" src="../../../../_static/js/theme.js"></script>

    

  
  <link rel="stylesheet" href="../../../../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../../../_static/pygments.css" type="text/css" />
  <link rel="stylesheet" href="../../../../_static/nlp_arch_theme.css" type="text/css" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto+Mono" type="text/css" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:100,900" type="text/css" />
    <link rel="index" title="Index" href="../../../../genindex.html" />
    <link rel="search" title="Search" href="../../../../search.html" /> 
</head>

<body class="wy-body-for-nav">

   
  <div class="wy-grid-for-nav">
    
    <nav data-toggle="wy-nav-shift" class="wy-nav-side">
      <div class="wy-side-scroll">
        <div class="wy-side-nav-search" >
          

          
            <a href="../../../../index.html">
          

          
            
            <img src="../../../../_static/logo.png" class="logo" alt="Logo"/>
          
          </a>

          

          
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../../../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>

          
        </div>

        <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
          
            
            
              
            
            
              <ul>
<li class="toctree-l1"><a class="reference internal" href="../../../../quick_start.html">Quick start</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../installation.html">Installation</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../publications.html">Publications</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../tutorials.html">Jupyter Tutorials</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../model_zoo.html">Model Zoo</a></li>
</ul>
<p class="caption"><span class="caption-text">NLP/NLU Models</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../../tagging/sequence_tagging.html">Sequence Tagging</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../sentiment.html">Sentiment Analysis</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../bist_parser.html">Dependency Parsing</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../intent.html">Intent Extraction</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../lm.html">Language Models</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../information_extraction.html">Information Extraction</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../transformers.html">Transformers</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../archived/additional.html">Additional Models</a></li>
</ul>
<p class="caption"><span class="caption-text">Optimized Models</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../../quantized_bert.html">Quantized BERT</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../transformers_distillation.html">Transformers Distillation</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../sparse_gnmt.html">Sparse Neural Machine Translation</a></li>
</ul>
<p class="caption"><span class="caption-text">Solutions</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../../absa_solution.html">Aspect Based Sentiment Analysis</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../term_set_expansion.html">Set Expansion</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../trend_analysis.html">Trend Analysis</a></li>
</ul>
<p class="caption"><span class="caption-text">For Developers</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../../generated_api/nlp_architect_api_index.html">nlp_architect API</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../developer_guide.html">Developer Guide</a></li>
</ul>

            
          
        </div>
      </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">

      
      <nav class="wy-nav-top" aria-label="top navigation">
        
          <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
          <a href="../../../../index.html">NLP Architect by Intel® AI Lab</a>
        
      </nav>


      <div class="wy-nav-content">
        
        <div class="rst-content">
        
          















<div role="navigation" aria-label="breadcrumbs navigation">

  <ul class="wy-breadcrumbs">
    
      <li><a href="../../../../index.html">Docs</a> &raquo;</li>
        
          <li><a href="../../../index.html">Module code</a> &raquo;</li>
        
          <li><a href="../../models.html">nlp_architect.models</a> &raquo;</li>
        
      <li>nlp_architect.models.transformers.sequence_classification</li>
    
    
      <li class="wy-breadcrumbs-aside">
        
      </li>
    
  </ul>

  
  <hr/>
</div>
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
            
  <h1>Source code for nlp_architect.models.transformers.sequence_classification</h1><div class="highlight"><pre>
<span></span><span class="c1"># ******************************************************************************</span>
<span class="c1"># Copyright 2017-2019 Intel Corporation</span>
<span class="c1">#</span>
<span class="c1"># Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);</span>
<span class="c1"># you may not use this file except in compliance with the License.</span>
<span class="c1"># You may obtain a copy of the License at</span>
<span class="c1">#</span>
<span class="c1">#     http://www.apache.org/licenses/LICENSE-2.0</span>
<span class="c1">#</span>
<span class="c1"># Unless required by applicable law or agreed to in writing, software</span>
<span class="c1"># distributed under the License is distributed on an &quot;AS IS&quot; BASIS,</span>
<span class="c1"># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.</span>
<span class="c1"># See the License for the specific language governing permissions and</span>
<span class="c1"># limitations under the License.</span>
<span class="c1"># ******************************************************************************</span>

<span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">os</span>
<span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">List</span><span class="p">,</span> <span class="n">Union</span>

<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">torch</span>
<span class="kn">from</span> <span class="nn">torch.utils.data</span> <span class="kn">import</span> <span class="n">DataLoader</span><span class="p">,</span> <span class="n">SequentialSampler</span><span class="p">,</span> <span class="n">TensorDataset</span>
<span class="kn">from</span> <span class="nn">transformers</span> <span class="kn">import</span> <span class="p">(</span>
    <span class="n">BertForSequenceClassification</span><span class="p">,</span>
    <span class="n">RobertaForSequenceClassification</span><span class="p">,</span>
    <span class="n">XLMForSequenceClassification</span><span class="p">,</span>
    <span class="n">XLNetForSequenceClassification</span><span class="p">,</span>
<span class="p">)</span>

<span class="kn">from</span> <span class="nn">nlp_architect.data.sequence_classification</span> <span class="kn">import</span> <span class="n">SequenceClsInputExample</span>
<span class="kn">from</span> <span class="nn">nlp_architect.models.transformers.base_model</span> <span class="kn">import</span> <span class="n">InputFeatures</span><span class="p">,</span> <span class="n">TransformerBase</span>
<span class="kn">from</span> <span class="nn">nlp_architect.models.transformers.quantized_bert</span> <span class="kn">import</span> <span class="n">QuantizedBertForSequenceClassification</span>
<span class="kn">from</span> <span class="nn">nlp_architect.utils.metrics</span> <span class="kn">import</span> <span class="n">accuracy</span>

<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="vm">__name__</span><span class="p">)</span>


<div class="viewcode-block" id="TransformerSequenceClassifier"><a class="viewcode-back" href="../../../../generated_api/nlp_architect.models.transformers.html#nlp_architect.models.transformers.sequence_classification.TransformerSequenceClassifier">[docs]</a><span class="k">class</span> <span class="nc">TransformerSequenceClassifier</span><span class="p">(</span><span class="n">TransformerBase</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Transformer sequence classifier</span>

<span class="sd">    Args:</span>
<span class="sd">        model_type (str): transformer base model type</span>
<span class="sd">        labels (List[str], optional): list of labels. Defaults to None.</span>
<span class="sd">        task_type (str, optional): task type (classification/regression). Defaults to</span>
<span class="sd">        classification.</span>
<span class="sd">        metric_fn ([type], optional): metric to use for evaluation. Defaults to</span>
<span class="sd">        simple_accuracy.</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="n">MODEL_CLASS</span> <span class="o">=</span> <span class="p">{</span>
        <span class="s2">&quot;bert&quot;</span><span class="p">:</span> <span class="n">BertForSequenceClassification</span><span class="p">,</span>
        <span class="s2">&quot;quant_bert&quot;</span><span class="p">:</span> <span class="n">QuantizedBertForSequenceClassification</span><span class="p">,</span>
        <span class="s2">&quot;xlnet&quot;</span><span class="p">:</span> <span class="n">XLNetForSequenceClassification</span><span class="p">,</span>
        <span class="s2">&quot;xlm&quot;</span><span class="p">:</span> <span class="n">XLMForSequenceClassification</span><span class="p">,</span>
        <span class="s2">&quot;roberta&quot;</span><span class="p">:</span> <span class="n">RobertaForSequenceClassification</span><span class="p">,</span>
    <span class="p">}</span>

    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span>
        <span class="bp">self</span><span class="p">,</span>
        <span class="n">model_type</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span>
        <span class="n">labels</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="nb">str</span><span class="p">]</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">task_type</span><span class="o">=</span><span class="s2">&quot;classification&quot;</span><span class="p">,</span>
        <span class="n">metric_fn</span><span class="o">=</span><span class="n">accuracy</span><span class="p">,</span>
        <span class="n">load_quantized</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
        <span class="o">*</span><span class="n">args</span><span class="p">,</span>
        <span class="o">**</span><span class="n">kwargs</span><span class="p">,</span>
    <span class="p">):</span>
        <span class="k">assert</span> <span class="n">model_type</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">MODEL_CLASS</span><span class="o">.</span><span class="n">keys</span><span class="p">(),</span> <span class="s2">&quot;unsupported model type&quot;</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">labels</span> <span class="o">=</span> <span class="n">labels</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">num_labels</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">labels</span><span class="p">)</span>
        <span class="nb">super</span><span class="p">(</span><span class="n">TransformerSequenceClassifier</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span>
            <span class="n">model_type</span><span class="p">,</span> <span class="n">labels</span><span class="o">=</span><span class="n">labels</span><span class="p">,</span> <span class="n">num_labels</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">num_labels</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span>
        <span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">model_class</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">MODEL_CLASS</span><span class="p">[</span><span class="n">model_type</span><span class="p">]</span>
        <span class="k">if</span> <span class="n">model_type</span> <span class="o">==</span> <span class="s2">&quot;quant_bert&quot;</span> <span class="ow">and</span> <span class="n">load_quantized</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">model</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model_class</span><span class="o">.</span><span class="n">from_pretrained</span><span class="p">(</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">model_name_or_path</span><span class="p">,</span>
                <span class="n">from_tf</span><span class="o">=</span><span class="nb">bool</span><span class="p">(</span><span class="s2">&quot;.ckpt&quot;</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">model_name_or_path</span><span class="p">),</span>
                <span class="n">config</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">config</span><span class="p">,</span>
                <span class="n">from_8bit</span><span class="o">=</span><span class="n">load_quantized</span><span class="p">,</span>
            <span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">model</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model_class</span><span class="o">.</span><span class="n">from_pretrained</span><span class="p">(</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">model_name_or_path</span><span class="p">,</span>
                <span class="n">from_tf</span><span class="o">=</span><span class="nb">bool</span><span class="p">(</span><span class="s2">&quot;.ckpt&quot;</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">model_name_or_path</span><span class="p">),</span>
                <span class="n">config</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">config</span><span class="p">,</span>
            <span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">task_type</span> <span class="o">=</span> <span class="n">task_type</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">metric_fn</span> <span class="o">=</span> <span class="n">metric_fn</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">device</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">n_gpus</span><span class="p">)</span>

<div class="viewcode-block" id="TransformerSequenceClassifier.train"><a class="viewcode-back" href="../../../../generated_api/nlp_architect.models.transformers.html#nlp_architect.models.transformers.sequence_classification.TransformerSequenceClassifier.train">[docs]</a>    <span class="k">def</span> <span class="nf">train</span><span class="p">(</span>
        <span class="bp">self</span><span class="p">,</span>
        <span class="n">train_data_set</span><span class="p">:</span> <span class="n">DataLoader</span><span class="p">,</span>
        <span class="n">dev_data_set</span><span class="p">:</span> <span class="n">Union</span><span class="p">[</span><span class="n">DataLoader</span><span class="p">,</span> <span class="n">List</span><span class="p">[</span><span class="n">DataLoader</span><span class="p">]]</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">test_data_set</span><span class="p">:</span> <span class="n">Union</span><span class="p">[</span><span class="n">DataLoader</span><span class="p">,</span> <span class="n">List</span><span class="p">[</span><span class="n">DataLoader</span><span class="p">]]</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">gradient_accumulation_steps</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">1</span><span class="p">,</span>
        <span class="n">per_gpu_train_batch_size</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">8</span><span class="p">,</span>
        <span class="n">max_steps</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span>
        <span class="n">num_train_epochs</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">3</span><span class="p">,</span>
        <span class="n">max_grad_norm</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mf">1.0</span><span class="p">,</span>
        <span class="n">logging_steps</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">50</span><span class="p">,</span>
        <span class="n">save_steps</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">100</span><span class="p">,</span>
    <span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Train a model</span>

<span class="sd">        Args:</span>
<span class="sd">            train_data_set (DataLoader): training data set</span>
<span class="sd">            dev_data_set (Union[DataLoader, List[DataLoader]], optional): development set.</span>
<span class="sd">            Defaults to None.</span>
<span class="sd">            test_data_set (Union[DataLoader, List[DataLoader]], optional): test set.</span>
<span class="sd">            Defaults to None.</span>
<span class="sd">            gradient_accumulation_steps (int, optional): num of gradient accumulation steps.</span>
<span class="sd">            Defaults to 1.</span>
<span class="sd">            per_gpu_train_batch_size (int, optional): per GPU train batch size. Defaults to 8.</span>
<span class="sd">            max_steps (int, optional): max steps. Defaults to -1.</span>
<span class="sd">            num_train_epochs (int, optional): number of train epochs. Defaults to 3.</span>
<span class="sd">            max_grad_norm (float, optional): max gradient normalization. Defaults to 1.0.</span>
<span class="sd">            logging_steps (int, optional): number of steps between logging. Defaults to 50.</span>
<span class="sd">            save_steps (int, optional): number of steps between model save. Defaults to 100.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_train</span><span class="p">(</span>
            <span class="n">train_data_set</span><span class="p">,</span>
            <span class="n">dev_data_set</span><span class="p">,</span>
            <span class="n">test_data_set</span><span class="p">,</span>
            <span class="n">gradient_accumulation_steps</span><span class="p">,</span>
            <span class="n">per_gpu_train_batch_size</span><span class="p">,</span>
            <span class="n">max_steps</span><span class="p">,</span>
            <span class="n">num_train_epochs</span><span class="p">,</span>
            <span class="n">max_grad_norm</span><span class="p">,</span>
            <span class="n">logging_steps</span><span class="o">=</span><span class="n">logging_steps</span><span class="p">,</span>
            <span class="n">save_steps</span><span class="o">=</span><span class="n">save_steps</span><span class="p">,</span>
        <span class="p">)</span></div>

<div class="viewcode-block" id="TransformerSequenceClassifier.evaluate_predictions"><a class="viewcode-back" href="../../../../generated_api/nlp_architect.models.transformers.html#nlp_architect.models.transformers.sequence_classification.TransformerSequenceClassifier.evaluate_predictions">[docs]</a>    <span class="k">def</span> <span class="nf">evaluate_predictions</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">logits</span><span class="p">,</span> <span class="n">label_ids</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Run evaluation of given logits and truth labels</span>

<span class="sd">        Args:</span>
<span class="sd">            logits: model logits</span>
<span class="sd">            label_ids: truth label ids</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">preds</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_postprocess_logits</span><span class="p">(</span><span class="n">logits</span><span class="p">)</span>
        <span class="n">label_ids</span> <span class="o">=</span> <span class="n">label_ids</span><span class="o">.</span><span class="n">numpy</span><span class="p">()</span>
        <span class="n">result</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">metric_fn</span><span class="p">(</span><span class="n">preds</span><span class="p">,</span> <span class="n">label_ids</span><span class="p">)</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">output_eval_file</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">output_path</span><span class="p">,</span> <span class="s2">&quot;eval_results.txt&quot;</span><span class="p">)</span>
        <span class="k">except</span> <span class="ne">TypeError</span><span class="p">:</span>
            <span class="n">output_eval_file</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">devnull</span>
        <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">output_eval_file</span><span class="p">,</span> <span class="s2">&quot;w&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">writer</span><span class="p">:</span>
            <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;***** Evaluation results *****&quot;</span><span class="p">)</span>
            <span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">result</span><span class="o">.</span><span class="n">keys</span><span class="p">()):</span>
                <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;  </span><span class="si">%s</span><span class="s2"> = </span><span class="si">%s</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="nb">str</span><span class="p">(</span><span class="n">result</span><span class="p">[</span><span class="n">key</span><span class="p">]))</span>
                <span class="n">writer</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">%s</span><span class="s2"> = </span><span class="si">%s</span><span class="se">\n</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="nb">str</span><span class="p">(</span><span class="n">result</span><span class="p">[</span><span class="n">key</span><span class="p">])))</span></div>

<div class="viewcode-block" id="TransformerSequenceClassifier.convert_to_tensors"><a class="viewcode-back" href="../../../../generated_api/nlp_architect.models.transformers.html#nlp_architect.models.transformers.sequence_classification.TransformerSequenceClassifier.convert_to_tensors">[docs]</a>    <span class="k">def</span> <span class="nf">convert_to_tensors</span><span class="p">(</span>
        <span class="bp">self</span><span class="p">,</span>
        <span class="n">examples</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="n">SequenceClsInputExample</span><span class="p">],</span>
        <span class="n">max_seq_length</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">128</span><span class="p">,</span>
        <span class="n">include_labels</span><span class="p">:</span> <span class="nb">bool</span> <span class="o">=</span> <span class="kc">True</span><span class="p">,</span>
    <span class="p">)</span> <span class="o">-&gt;</span> <span class="n">TensorDataset</span><span class="p">:</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Convert examples to tensor dataset</span>

<span class="sd">        Args:</span>
<span class="sd">            examples (List[SequenceClsInputExample]): examples</span>
<span class="sd">            max_seq_length (int, optional): max sequence length. Defaults to 128.</span>
<span class="sd">            include_labels (bool, optional): include labels. Defaults to True.</span>

<span class="sd">        Returns:</span>
<span class="sd">            TensorDataset:</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">features</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_convert_examples_to_features</span><span class="p">(</span>
            <span class="n">examples</span><span class="p">,</span>
            <span class="n">max_seq_length</span><span class="p">,</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">tokenizer</span><span class="p">,</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">task_type</span><span class="p">,</span>
            <span class="n">include_labels</span><span class="p">,</span>
            <span class="n">pad_on_left</span><span class="o">=</span><span class="nb">bool</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model_type</span> <span class="ow">in</span> <span class="p">[</span><span class="s2">&quot;xlnet&quot;</span><span class="p">]),</span>
            <span class="n">pad_token</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">tokenizer</span><span class="o">.</span><span class="n">convert_tokens_to_ids</span><span class="p">([</span><span class="bp">self</span><span class="o">.</span><span class="n">tokenizer</span><span class="o">.</span><span class="n">pad_token</span><span class="p">])[</span><span class="mi">0</span><span class="p">],</span>
            <span class="n">pad_token_segment_id</span><span class="o">=</span><span class="mi">4</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">model_type</span> <span class="ow">in</span> <span class="p">[</span><span class="s2">&quot;xlnet&quot;</span><span class="p">]</span> <span class="k">else</span> <span class="mi">0</span><span class="p">,</span>
        <span class="p">)</span>
        <span class="c1"># Convert to Tensors and build dataset</span>
        <span class="n">all_input_ids</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">tensor</span><span class="p">([</span><span class="n">f</span><span class="o">.</span><span class="n">input_ids</span> <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">features</span><span class="p">],</span> <span class="n">dtype</span><span class="o">=</span><span class="n">torch</span><span class="o">.</span><span class="n">long</span><span class="p">)</span>
        <span class="n">all_input_mask</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">tensor</span><span class="p">([</span><span class="n">f</span><span class="o">.</span><span class="n">input_mask</span> <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">features</span><span class="p">],</span> <span class="n">dtype</span><span class="o">=</span><span class="n">torch</span><span class="o">.</span><span class="n">long</span><span class="p">)</span>
        <span class="n">all_segment_ids</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">tensor</span><span class="p">([</span><span class="n">f</span><span class="o">.</span><span class="n">segment_ids</span> <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">features</span><span class="p">],</span> <span class="n">dtype</span><span class="o">=</span><span class="n">torch</span><span class="o">.</span><span class="n">long</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">include_labels</span><span class="p">:</span>
            <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">task_type</span> <span class="o">==</span> <span class="s2">&quot;classification&quot;</span><span class="p">:</span>
                <span class="n">all_label_ids</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">tensor</span><span class="p">([</span><span class="n">f</span><span class="o">.</span><span class="n">label_id</span> <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">features</span><span class="p">],</span> <span class="n">dtype</span><span class="o">=</span><span class="n">torch</span><span class="o">.</span><span class="n">long</span><span class="p">)</span>
            <span class="k">elif</span> <span class="bp">self</span><span class="o">.</span><span class="n">task_type</span> <span class="o">==</span> <span class="s2">&quot;regression&quot;</span><span class="p">:</span>
                <span class="n">all_label_ids</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">tensor</span><span class="p">([</span><span class="n">f</span><span class="o">.</span><span class="n">label_id</span> <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">features</span><span class="p">],</span> <span class="n">dtype</span><span class="o">=</span><span class="n">torch</span><span class="o">.</span><span class="n">float</span><span class="p">)</span>
            <span class="k">return</span> <span class="n">TensorDataset</span><span class="p">(</span><span class="n">all_input_ids</span><span class="p">,</span> <span class="n">all_input_mask</span><span class="p">,</span> <span class="n">all_segment_ids</span><span class="p">,</span> <span class="n">all_label_ids</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">TensorDataset</span><span class="p">(</span><span class="n">all_input_ids</span><span class="p">,</span> <span class="n">all_input_mask</span><span class="p">,</span> <span class="n">all_segment_ids</span><span class="p">)</span></div>

<div class="viewcode-block" id="TransformerSequenceClassifier.inference"><a class="viewcode-back" href="../../../../generated_api/nlp_architect.models.transformers.html#nlp_architect.models.transformers.sequence_classification.TransformerSequenceClassifier.inference">[docs]</a>    <span class="k">def</span> <span class="nf">inference</span><span class="p">(</span>
        <span class="bp">self</span><span class="p">,</span>
        <span class="n">examples</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="n">SequenceClsInputExample</span><span class="p">],</span>
        <span class="n">max_seq_length</span><span class="p">:</span> <span class="nb">int</span><span class="p">,</span>
        <span class="n">batch_size</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">64</span><span class="p">,</span>
        <span class="n">evaluate</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
    <span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Run inference on given examples</span>

<span class="sd">        Args:</span>
<span class="sd">            examples (List[SequenceClsInputExample]): examples</span>
<span class="sd">            batch_size (int, optional): batch size. Defaults to 64.</span>

<span class="sd">        Returns:</span>
<span class="sd">            logits</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">data_set</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">convert_to_tensors</span><span class="p">(</span>
            <span class="n">examples</span><span class="p">,</span> <span class="n">max_seq_length</span><span class="o">=</span><span class="n">max_seq_length</span><span class="p">,</span> <span class="n">include_labels</span><span class="o">=</span><span class="n">evaluate</span>
        <span class="p">)</span>
        <span class="n">inf_sampler</span> <span class="o">=</span> <span class="n">SequentialSampler</span><span class="p">(</span><span class="n">data_set</span><span class="p">)</span>
        <span class="n">inf_dataloader</span> <span class="o">=</span> <span class="n">DataLoader</span><span class="p">(</span><span class="n">data_set</span><span class="p">,</span> <span class="n">sampler</span><span class="o">=</span><span class="n">inf_sampler</span><span class="p">,</span> <span class="n">batch_size</span><span class="o">=</span><span class="n">batch_size</span><span class="p">)</span>
        <span class="n">logits</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_evaluate</span><span class="p">(</span><span class="n">inf_dataloader</span><span class="p">)</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">evaluate</span><span class="p">:</span>
            <span class="n">preds</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_postprocess_logits</span><span class="p">(</span><span class="n">logits</span><span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">logits</span><span class="p">,</span> <span class="n">label_ids</span> <span class="o">=</span> <span class="n">logits</span>
            <span class="n">preds</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_postprocess_logits</span><span class="p">(</span><span class="n">logits</span><span class="p">)</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">evaluate_predictions</span><span class="p">(</span><span class="n">logits</span><span class="p">,</span> <span class="n">label_ids</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">preds</span></div>

    <span class="k">def</span> <span class="nf">_postprocess_logits</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">logits</span><span class="p">):</span>
        <span class="n">preds</span> <span class="o">=</span> <span class="n">logits</span><span class="o">.</span><span class="n">numpy</span><span class="p">()</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">task_type</span> <span class="o">==</span> <span class="s2">&quot;classification&quot;</span><span class="p">:</span>
            <span class="n">preds</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">argmax</span><span class="p">(</span><span class="n">preds</span><span class="p">,</span> <span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
        <span class="k">elif</span> <span class="bp">self</span><span class="o">.</span><span class="n">task_type</span> <span class="o">==</span> <span class="s2">&quot;regression&quot;</span><span class="p">:</span>
            <span class="n">preds</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">squeeze</span><span class="p">(</span><span class="n">preds</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">preds</span>

    <span class="k">def</span> <span class="nf">_convert_examples_to_features</span><span class="p">(</span>
        <span class="bp">self</span><span class="p">,</span>
        <span class="n">examples</span><span class="p">,</span>
        <span class="n">max_seq_length</span><span class="p">,</span>
        <span class="n">tokenizer</span><span class="p">,</span>
        <span class="n">task_type</span><span class="p">,</span>
        <span class="n">include_labels</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span>
        <span class="n">pad_on_left</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
        <span class="n">pad_token</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span>
        <span class="n">pad_token_segment_id</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span>
        <span class="n">mask_padding_with_zero</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span>
    <span class="p">):</span>
        <span class="sd">&quot;&quot;&quot; Loads a data file into a list of `InputBatch`s</span>
<span class="sd">            `cls_token_at_end` define the location of the CLS token:</span>
<span class="sd">                - False (Default, BERT/XLM pattern): [CLS] + A + [SEP] + B + [SEP]</span>
<span class="sd">                - True (XLNet/GPT pattern): A + [SEP] + B + [SEP] + [CLS]</span>
<span class="sd">            `cls_token_segment_id` define the segment id associated to the CLS token</span>
<span class="sd">            (0 for BERT, 2 for XLNet)</span>
<span class="sd">        &quot;&quot;&quot;</span>

        <span class="k">if</span> <span class="n">include_labels</span><span class="p">:</span>
            <span class="n">label_map</span> <span class="o">=</span> <span class="p">{</span><span class="n">label</span><span class="p">:</span> <span class="n">i</span> <span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">label</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">labels</span><span class="p">)}</span>

        <span class="n">features</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="k">for</span> <span class="p">(</span><span class="n">ex_index</span><span class="p">,</span> <span class="n">example</span><span class="p">)</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">examples</span><span class="p">):</span>
            <span class="k">if</span> <span class="n">ex_index</span> <span class="o">%</span> <span class="mi">10000</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
                <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;Writing example </span><span class="si">%d</span><span class="s2"> of </span><span class="si">%d</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">ex_index</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">examples</span><span class="p">))</span>

            <span class="n">inputs</span> <span class="o">=</span> <span class="n">tokenizer</span><span class="o">.</span><span class="n">encode_plus</span><span class="p">(</span>
                <span class="n">example</span><span class="o">.</span><span class="n">text</span><span class="p">,</span> <span class="n">example</span><span class="o">.</span><span class="n">text_b</span><span class="p">,</span> <span class="n">add_special_tokens</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">max_length</span><span class="o">=</span><span class="n">max_seq_length</span><span class="p">,</span>
            <span class="p">)</span>
            <span class="n">input_ids</span><span class="p">,</span> <span class="n">token_type_ids</span> <span class="o">=</span> <span class="n">inputs</span><span class="p">[</span><span class="s2">&quot;input_ids&quot;</span><span class="p">],</span> <span class="n">inputs</span><span class="p">[</span><span class="s2">&quot;token_type_ids&quot;</span><span class="p">]</span>

            <span class="n">attention_mask</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span> <span class="k">if</span> <span class="n">mask_padding_with_zero</span> <span class="k">else</span> <span class="mi">0</span><span class="p">]</span> <span class="o">*</span> <span class="nb">len</span><span class="p">(</span><span class="n">input_ids</span><span class="p">)</span>

            <span class="n">padding_length</span> <span class="o">=</span> <span class="n">max_seq_length</span> <span class="o">-</span> <span class="nb">len</span><span class="p">(</span><span class="n">input_ids</span><span class="p">)</span>
            <span class="k">if</span> <span class="n">pad_on_left</span><span class="p">:</span>
                <span class="n">input_ids</span> <span class="o">=</span> <span class="p">([</span><span class="n">pad_token</span><span class="p">]</span> <span class="o">*</span> <span class="n">padding_length</span><span class="p">)</span> <span class="o">+</span> <span class="n">input_ids</span>
                <span class="n">attention_mask</span> <span class="o">=</span> <span class="p">(</span>
                    <span class="p">[</span><span class="mi">0</span> <span class="k">if</span> <span class="n">mask_padding_with_zero</span> <span class="k">else</span> <span class="mi">1</span><span class="p">]</span> <span class="o">*</span> <span class="n">padding_length</span>
                <span class="p">)</span> <span class="o">+</span> <span class="n">attention_mask</span>
                <span class="n">token_type_ids</span> <span class="o">=</span> <span class="p">([</span><span class="n">pad_token_segment_id</span><span class="p">]</span> <span class="o">*</span> <span class="n">padding_length</span><span class="p">)</span> <span class="o">+</span> <span class="n">token_type_ids</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="n">input_ids</span> <span class="o">=</span> <span class="n">input_ids</span> <span class="o">+</span> <span class="p">([</span><span class="n">pad_token</span><span class="p">]</span> <span class="o">*</span> <span class="n">padding_length</span><span class="p">)</span>
                <span class="n">attention_mask</span> <span class="o">=</span> <span class="n">attention_mask</span> <span class="o">+</span> <span class="p">(</span>
                    <span class="p">[</span><span class="mi">0</span> <span class="k">if</span> <span class="n">mask_padding_with_zero</span> <span class="k">else</span> <span class="mi">1</span><span class="p">]</span> <span class="o">*</span> <span class="n">padding_length</span>
                <span class="p">)</span>
                <span class="n">token_type_ids</span> <span class="o">=</span> <span class="n">token_type_ids</span> <span class="o">+</span> <span class="p">([</span><span class="n">pad_token_segment_id</span><span class="p">]</span> <span class="o">*</span> <span class="n">padding_length</span><span class="p">)</span>

            <span class="k">assert</span> <span class="nb">len</span><span class="p">(</span><span class="n">input_ids</span><span class="p">)</span> <span class="o">==</span> <span class="n">max_seq_length</span>
            <span class="k">assert</span> <span class="nb">len</span><span class="p">(</span><span class="n">attention_mask</span><span class="p">)</span> <span class="o">==</span> <span class="n">max_seq_length</span>
            <span class="k">assert</span> <span class="nb">len</span><span class="p">(</span><span class="n">token_type_ids</span><span class="p">)</span> <span class="o">==</span> <span class="n">max_seq_length</span>

            <span class="k">if</span> <span class="n">include_labels</span><span class="p">:</span>
                <span class="k">if</span> <span class="n">task_type</span> <span class="o">==</span> <span class="s2">&quot;classification&quot;</span><span class="p">:</span>
                    <span class="n">label_id</span> <span class="o">=</span> <span class="n">label_map</span><span class="p">[</span><span class="n">example</span><span class="o">.</span><span class="n">label</span><span class="p">]</span>
                <span class="k">elif</span> <span class="n">task_type</span> <span class="o">==</span> <span class="s2">&quot;regression&quot;</span><span class="p">:</span>
                    <span class="n">label_id</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="n">example</span><span class="o">.</span><span class="n">label</span><span class="p">)</span>
                <span class="k">else</span><span class="p">:</span>
                    <span class="k">raise</span> <span class="ne">KeyError</span><span class="p">(</span><span class="n">task_type</span><span class="p">)</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="n">label_id</span> <span class="o">=</span> <span class="kc">None</span>

            <span class="n">features</span><span class="o">.</span><span class="n">append</span><span class="p">(</span>
                <span class="n">InputFeatures</span><span class="p">(</span>
                    <span class="n">input_ids</span><span class="o">=</span><span class="n">input_ids</span><span class="p">,</span>
                    <span class="n">input_mask</span><span class="o">=</span><span class="n">attention_mask</span><span class="p">,</span>
                    <span class="n">segment_ids</span><span class="o">=</span><span class="n">token_type_ids</span><span class="p">,</span>
                    <span class="n">label_id</span><span class="o">=</span><span class="n">label_id</span><span class="p">,</span>
                <span class="p">)</span>
            <span class="p">)</span>
        <span class="k">return</span> <span class="n">features</span></div>
</pre></div>

           </div>
           
          </div>
          <footer>
  

  <hr/>

  <div role="contentinfo">
    <p>

    </p>
  </div>
  Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/rtfd/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. 

</footer>

        </div>
      </div>

    </section>

  </div>
  


  <script type="text/javascript">
      jQuery(function () {
          SphinxRtdTheme.Navigation.enable(true);
      });
  </script>

  
  
    
   

</body>
</html>